package Lab12;

import java.io.*;

public class FileReader {
    static void readCharacters() throws IOException {

        int lineCnt = 0;
        int charactersCnt = 0;
        int wordsCnt = 0;
        try {
//          FileInputStream是实际对应物理文件的源
//                  BufferedInputStream是对以上源的包装
//          BufferedInputStream 有个内部缓冲区当read时会先把缓冲区填满，然后下次读取是直接从缓冲区读取。
//          当读取的位置大于缓冲区时会再一次加载缓冲区。
            String encoding = "GBK";
//    https://www.cnblogs.com/manongxiaojiang/archive/2012/10/13/2722068.html
            String filePath = "src/Lab12/Loan.java";
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { //判断文件是否存在

                DataInputStream in = new DataInputStream(new FileInputStream(filePath));

                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));

                BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));

//        https://blog.csdn.net/weixin_34214500/article/details/92510930

//        https://blog.csdn.net/sinyui/article/details/52263501
                String lineTxt = null;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    String[] s = lineTxt.split(" ");
                    for (String s1 : s) {
                        if (s1.equals("") || s1.equals("\n")) continue;
                        wordsCnt++;
                    }

                    lineCnt++;

                }

                bufferedReader.close();

                while (inputStream.read() != -1) {
                    charactersCnt++;
                }
                inputStream.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        System.out.println("File Loan.java has");
        System.out.println(charactersCnt + " characters");
        System.out.println(wordsCnt + " words");
        System.out.println(lineCnt + " lines");

//      File Loan.java has
//      1920 characters
//      210 words
//      71 lines

    }

    public static void main(String[] args) throws IOException {
        readCharacters();
    }


}
